package cn.supermarket.config;


//import cn.supermarket.security.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)  //开启全局方法安全性，通过该注解配置权限功能
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

//    @Autowired
//    JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public PasswordEncoder passwordEncoders() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 原有模式中，登录成功后自动将用户信息到Session中且跳转页面
     * 自动装配AuthenticationManager对象
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    protected void configure(HttpSecurity http) throws Exception {

        String[] url = {"/admin/login",
                "/doc.html",
                "/*/js/**",
                "/*/css/**",
                "/swagger-resources",
                "/v2/api-docs*",
                "/favicon.ico",
                "/**"};

        //禁用防跨域攻击
        http.csrf().disable();

        //url白名单
        http.authorizeRequests()     //需要授权才可以访问
                .antMatchers(url)       //匹配一些路径
                .permitAll()         //允许直接访问（不需要认证和授权）
                .anyRequest()        //匹配除了以上配置的其他请求
                .authenticated();    //都需要认证
        //注册处理JWT的过滤器
        //此过滤器必须在Security处理登录之前
//        http.addFilterBefore(jwtAuthenticationFilter,
//                UsernamePasswordAuthenticationFilter.class);

    }
}
